package com.pianzhu.blockchainemr.service.impl;

import com.pianzhu.blockchainemr.mapper.LoginMapper;
import com.pianzhu.blockchainemr.pojo.User;
import com.pianzhu.blockchainemr.service.LoginService;
import com.pianzhu.blockchainemr.utils.JWTUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class);
    @Autowired
    private LoginMapper loginMapper;

    public User login(String username, String password) {
        User user = loginMapper.login(username, password);
        if (user!= null && user.getPassword().equals(password)) {
            Map<String, Object> claims = new HashMap<String, Object>();
            claims.put("id", user.getId());
            claims.put("username", username);
            claims.put("usertype", user.getUsertype());
            //生成token
            String token = JWTUtils.createJWT(claims);
            log.info("login success, token: " + token);
            user.setToken(token);
            user.setPassword(null);
            return user;
        }
        return null;
    }

    @Override
    public void logout(String username) {
        loginMapper.logout(LocalDateTime.now(), username);
    }
}
